import json
import time
from urllib.parse import urlparse, parse_qs

class SunnyEmulator:
    def __init__(self):
        self.captured_data = []
        self.target_domains = ['api.kuaishou.com']  # 设置目标域名
        
    def capture_request(self, request):
        """捕获请求数据"""
        try:
            url = request.get('url', '')
            domain = urlparse(url).netloc
            
            # 只捕获目标域名的请求
            if domain in self.target_domains:
                data = {
                    'timestamp': int(time.time() * 1000),
                    'method': request.get('method', ''),
                    'url': url,
                    'headers': request.get('headers', {}),
                    'body': request.get('body', ''),
                    'query_params': parse_qs(urlparse(url).query)
                }
                
                # 提取关键参数
                if 'sig' in data['query_params']:
                    data['signature'] = data['query_params']['sig'][0]
                
                self.captured_data.append(data)
                print(f"捕获到请求: {url}")
                
                # 实时保存
                self.save_capture()
                
        except Exception as e:
            print(f"捕获请求失败: {e}")
    
    def save_capture(self, filename='emulator_capture.json'):
        """保存抓包数据"""
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(self.captured_data, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"保存数据失败: {e}")
    
    def analyze_signatures(self):
        """分析签名"""
        signatures = {}
        for data in self.captured_data:
            if 'signature' in data:
                sig = data['signature']
                if sig not in signatures:
                    signatures[sig] = []
                signatures[sig].append({
                    'url': data['url'],
                    'timestamp': data['timestamp']
                })
        
        print("\n签名分析:")
        for sig, requests in signatures.items():
            print(f"\n签名: {sig}")
            print(f"使用次数: {len(requests)}")
            print("请求列表:")
            for req in requests:
                print(f"- {req['url']}")
    
    def extract_params(self):
        """提取所有参数"""
        all_params = set()
        for data in self.captured_data:
            # 从URL参数中提取
            params = data.get('query_params', {})
            all_params.update(params.keys())
            
            # 从请求体中提取
            try:
                if isinstance(data['body'], str):
                    body = json.loads(data['body'])
                    if isinstance(body, dict):
                        all_params.update(body.keys())
            except:
                pass
        
        print("\n所有参数列表:")
        for param in sorted(all_params):
            print(f"- {param}")

def main():
    emulator = SunnyEmulator()
    
    # 模拟请求数据
    test_request = {
        'method': 'POST',
        'url': 'https://api.kuaishou.com/rest/n/user/login?sig=test123&token=abc',
        'headers': {
            'User-Agent': 'kwai-android',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        'body': '{"mobile": "18229650633"}'
    }
    
    # 捕获请求
    emulator.capture_request(test_request)
    
    # 分析数据
    emulator.analyze_signatures()
    emulator.extract_params()

if __name__ == '__main__':
    main() 